package com.wenchao.serialport;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.example.x6.serial.SerialPort;

import java.io.File;
import java.io.IOException;

/**
 * 【类的描述】SerialPortService
 *
 * @author zhangwenchao
 * @date 2021-12-29
 */
public class SerialPortService extends Service {

    public static final String RECEIVER_ACTION_NAME = "com.wenchao.SerialPortDataReceiver";
    private static SerialPort serialPort;
    private static final String DEV_PATH = "dev_path";
    private static final String BAUD_RATE = "baud_rate";
    private static final String FLAGS = "flags";
    private SerialPortReadThread serialPortReadThread;

    public static void startService(Context context, String devPath, int baudRate) {
        Intent intent = new Intent(context, SerialPortService.class);
        intent.putExtra(DEV_PATH, devPath);
        intent.putExtra(BAUD_RATE, baudRate);
        context.startService(intent);
    }

    public static SerialPort getSerialPort() {
        return serialPort;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String devPath = intent.getStringExtra(DEV_PATH);
        int baudRate = intent.getIntExtra(BAUD_RATE, 0);
        int mFlags = intent.getIntExtra(FLAGS, 0);

        if (TextUtils.isEmpty(devPath) || baudRate == 0) {
            throw new IllegalArgumentException("参数不合法");
        }

        try {
            serialPort = new SerialPort(new File(devPath), baudRate, mFlags);
        } catch (IOException e) {
            e.printStackTrace();
        }

        serialPortReadThread = new SerialPortReadThread(this, serialPort);
        serialPortReadThread.start();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (serialPortReadThread != null) {
            serialPortReadThread.interrupt();
        }

        if (serialPort != null) {
            serialPort.close();
        }
    }

}
